/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.source.web.title;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thinkgem.jeesite.common.utils.I18nUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.publish.entity.EleSourceGroupPublish;
import com.thinkgem.jeesite.modules.source.entity.EleSource;
import com.thinkgem.jeesite.modules.source.entity.EleSourceGroup;
import com.thinkgem.jeesite.modules.source.entity.EleSourceMultimedia;
import com.thinkgem.jeesite.modules.source.entity.title.EleSourceTitle;
import com.thinkgem.jeesite.modules.source.service.EleSourceGroupService;
import com.thinkgem.jeesite.modules.source.service.title.EleSourceTitleService;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.SwitchUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.templet.service.EleTempletService;

/**
 * 标题管理Controller
 * @author ZC
 * @version 2017-06-16
 */
@Controller
@RequestMapping(value = "${adminPath}/source/title/eleSourceTitle")
public class EleSourceTitleController extends BaseController {

	@Autowired
	private EleSourceTitleService eleSourceTitleService;
	@Autowired
	private EleSourceGroupService eleSourceGroupService;	
	@Autowired
	private OfficeService officeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private EleEquipmentService eleEquipmentService;
	@Autowired
	private EleTempletService eleTempletService;	
	@ModelAttribute
	public EleSourceTitle get(@RequestParam(required=false) String id) {
		EleSourceTitle entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eleSourceTitleService.get(id);
		}
		if (entity == null){
			entity = new EleSourceTitle();
		}
		return entity;
	}
	
	@RequiresPermissions("source:title:eleSourceTitle:view")
	@RequestMapping(value = {"list", ""})
	public String list(EleSourceTitle eleSourceTitle, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		List<User> list = null;
		if(user.isAdmin()) {
			list = systemService.findAllUsers(user);
		}else {
			list = systemService.findAllUsersInCompany(user);
			list.add(UserUtils.getAdminUser());		
		}		
		eleSourceTitle.setUsers(list);
		Page<EleSourceTitle> page = eleSourceTitleService.findPage(new Page<EleSourceTitle>(request, response), eleSourceTitle); 
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		page.setLocale(locale);
		for(EleSourceTitle e:page.getList()) {
			e.setGroup(eleSourceGroupService.getGroupById(e.getGroupId()));
		}
		model.addAttribute("page", page);
		return "modules/source/title/eleSourceTitleList";
	}

	@RequiresPermissions("source:title:eleSourceTitle:view")
	@RequestMapping(value = "form")
	public String form(EleSourceTitle eleSourceTitle, Model model,HttpServletRequest request) {
		model.addAttribute("eleSourceTitle", eleSourceTitle);
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		model.addAttribute("language", locale.getLanguage());
		return "modules/source/title/eleSourceTitleForm";
	}

	@RequiresPermissions("source:title:eleSourceTitle:edit")
	@RequestMapping(value = "save")
	public String save(EleSourceTitle eleSourceTitle, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) {
		if (!beanValidator(model, eleSourceTitle)){
			return form(eleSourceTitle, model,request);
		}
		eleSourceTitleService.save(eleSourceTitle);

		if(!StringUtils.isEmpty(eleSourceTitle.getGroupId())) {
			eleSourceGroupService.deleteFromDB(eleSourceTitle.getGroupId());
		}
		
		EleSourceGroup eleSourceGroup = null;
		eleSourceGroup = new EleSourceGroup();
		EleSource source = new EleSource();
		source.setId("");
		source.setType("title");
		source.setName("TitleGenerated");
		source.setContent(eleSourceTitle.getId());
			
		List<EleSource> esList = Lists.newArrayList();
		esList.add(source);
		eleSourceGroup.setEleSourceList(esList);
		eleSourceGroup.setVisible("0");
		eleSourceGroup.setType("title");
		
		boolean noNeedCheck = UserUtils.getSubject().isPermitted("source:eleSourceGroup:check")
                || SwitchUtils.isClose("source:eleSourceGroup:check");
		if(noNeedCheck){
			eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_NORMAL);
		}else{
			eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_AUDIT);
		}
		eleSourceGroup.setName(eleSourceTitle.getName());

		
		System.out.println(JsonMapper.toJsonString((eleSourceTitle)));

		eleSourceGroupService.save(eleSourceGroup);
		boolean result = true;
		String basePath = Global.getUserfilesBaseDir();
		try {
			result = eleTempletService.createPackageForSourceGroup(eleSourceGroup, basePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		eleSourceTitleService.updateGroupId(eleSourceGroup.getId(), eleSourceTitle.getId());
		//System.out.println(JSONObject.toJSONString(eleSourceTitle));
		String locale = I18nUtils.getLocaleStr();
		String msg = "保存标题成功";
		String msg2 = "保存失败，请重新编辑";
		if(Global.US.equals(locale)){
			msg = "title saved";
			msg2 = "Save failed, please edit again";
		}
		if(result) {
			addMessage(redirectAttributes, msg);
			return "redirect:"+Global.getAdminPath()+"/source/title/eleSourceTitle/?repage";
		} else {
			addMessage(redirectAttributes, msg2);
			return "redirect:"+ request.getHeader("referer");
		}
	}
	
	@RequiresPermissions("source:title:eleSourceTitle:edit")
	@RequestMapping(value = "delete")
	public String delete(EleSourceTitle eleSourceTitle, RedirectAttributes redirectAttributes) {
		eleSourceTitleService.delete(eleSourceTitle);
		String locale = I18nUtils.getLocaleStr();
		String msg = "删除标题成功";
		if(Global.US.equals(locale)){
			msg = "title deleted";
		}
		addMessage(redirectAttributes, msg);
		return "redirect:"+Global.getAdminPath()+"/source/title/eleSourceTitle/?repage";
	}
	@RequiresPermissions("source:title:eleSourceTitle:edit")
	@RequestMapping(value = "applypublish")
	public String applypublish(EleSourceTitle eleSourceTitle, RedirectAttributes redirectAttributes,Model model) {
		EleSourceGroup eleSourceGroup = eleSourceGroupService.getGroupById(eleSourceTitle.getGroupId());
		if(!EleSourceGroup.DEL_FLAG_NORMAL.equals(eleSourceGroup.getDelFlag())) {
			String locale = I18nUtils.getLocaleStr();
			String msg = "该资源未通过审批，不能发布";
			if(Global.US.equals(locale)){
				msg = "The resource is not approved and can not be released";
			}
			addMessage(redirectAttributes, msg);
			return "redirect:"+Global.getAdminPath()+"/source/title/eleSourceTitle/?repage";
		}
		String basePath = Global.getUserfilesBaseDir();
		try {
			eleTempletService.createPackageForSourceGroup(eleSourceGroup, basePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		eleSourceTitleService.updateGroupId(eleSourceGroup.getId(), eleSourceTitle.getId());
		// Edited by jyz (2018.5)
		if(!eleSourceGroupService.resourceFileExistById(eleSourceTitle.getGroupId())) {
			String locale = I18nUtils.getLocaleStr();
			String msg = "该资源对应文件不存在，请重新编辑保存后再尝试";
			if(Global.US.equals(locale)){
				msg = "The resource corresponding file does not exist, please re-edit it and try again";
			}
			addMessage(redirectAttributes, msg);
			return "redirect:"+Global.getAdminPath()+"/source/title/eleSourceTitle/?repage";
		}

		EleEquipment eleEquipment = new EleEquipment();
		List<Office> listTree = new ArrayList<>();

        User current = UserUtils.getUser();
        List<User> resultList = systemService.getBranchForUserWithSelf(current);
		Set<String> ids = new HashSet<String>();
		for(User temuser:resultList){
			System.out.println(temuser.getLoginName());
			 String officeId = temuser.getOffice().getId();
			 String companyId = temuser.getCompany().getId();
			ids.add(officeId);
			ids.add(companyId);
		}
		List<Office> listOffice = officeService.findList(true);
		
	
		Set<String> officeIds = new HashSet<>();
		Set<String> eqIds = new HashSet<>();
		for(User tmp:resultList){
			EleEquipment eleEquipmentTmp = new EleEquipment();
			eleEquipmentTmp.setCompany(tmp.getCompany());
			eleEquipmentTmp.setOffice(tmp.getOffice());

			List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipmentTmp);
			for (EleEquipment equipment : listEquipment) {
				officeIds.add(equipment.getCompany().getId());
				officeIds.add(equipment.getOffice().getId());
				if(eqIds.contains(equipment.getId())){
					continue;
				}
				eqIds.add(equipment.getId());
				Office Office = new Office();
				Office.setId(equipment.getId());
				Office.setParent(new Office(equipment.getOffice().getId()));
				Office.setAddress(equipment.getCode());
				Office.setEmail(equipment.getType().getName());
				Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
				Office.setRemarks(equipment.getRemarks());
				if("1".equals(equipment.getState())){
					Office.setGrade("在线");
				}else{
					Office.setGrade("离线");
				}
				Office.setPhone("");
				Office.setZipCode(equipment.getName());

				listTree.add(Office);
			}
		}
		System.out.println(listTree.size()+"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");

		Set<String> resultSet = new HashSet<String>();
		for (String oid : officeIds) {
			resultSet.add(oid);
			Office tmp = officeService.get(oid);
			for (int i = 0; i < listOffice.size(); i++) {
				Office item = listOffice.get(i);
				if (item.getId().equals(tmp.getParentId())) {
					System.out.println(item);
					tmp = item;
					i = -1;
					resultSet.add(item.getId());
				}
			}
		}
		for(String oid:resultSet){
			Office item = officeService.get(oid);
			item.setAddress(null);
			item.setEmail(null);
			item.setFax(null);
			item.setRemarks(null);
			item.setGrade(null);
			item.setPhone("display:none;");
			item.setZipCode("");

			listTree.add(item);
		}
			model.addAttribute("list", listTree);
			model.addAttribute("user", current);
			model.addAttribute("eleEquipment", eleEquipment);
			model.addAttribute("eleSourceGroup", eleSourceGroup);
			model.addAttribute("resourcetype", "title");

			return "modules/source/eleSourceGroupPublish";
	}
}